﻿using SarjetLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MediaMetadataTagEditor_cmd
{
  internal class Program
  {
    static void Main(string[] args)
    {
      var exifpath = Path.Combine(Environment.CurrentDirectory, "exiftool.exe");

      var log = Path.Combine(Environment.CurrentDirectory, "MediaMetadataTagEditor_cmd.log");
      if (Debugger.IsAttached)
      {
        args = new string[] {
          "-d",
          @"./",
          "-r",
          @".+\.(mp4)$",
          //"-p",
          //"-f",
          //@"L123.mp4",
          "-regexName",
          @"(?<name>.+)\.mp4$",
          "-Title",
          "\"$name$\"",
          "-dbg",
           };
      }

      if (!File.Exists(exifpath))
      {
        Console.WriteLine($"{"missing exe file: \"./exiftool.exe\""}");
        Console.ReadKey();
        return;
      }

      CmdAnalysisArgs_t cmd = new CmdAnalysisArgs_t();
      cmd.Analysis(args);
      if (!cmd.CheckRelPath())
      {
        Console.WriteLine(CmdAnalysisArgs_t.HelperString);
        Console.ReadKey();
        return;
      }

      Console.WriteLine($"{"Tools",CmdAnalysisArgs_t.nWidth}: {exifpath}");
      Console.WriteLine();
      Console.WriteLine("Running...");

      if (!string.IsNullOrEmpty(cmd.file))
      {
        string file = cmd.file;
        Console.WriteLine($"{"-File",CmdAnalysisArgs_t.nWidth}: {file}");
        Console.WriteLine(file);
        Task_ExifFile(cmd, file);
        Task_RunExiftool(cmd, file, exifpath);
      }
      if (!string.IsNullOrEmpty(cmd.dir))
      {
        Console.WriteLine($"{"-Dir",CmdAnalysisArgs_t.nWidth}: {cmd.dir}");
        var afiles = Directory.GetFiles(cmd.dir, "*", SearchOption.AllDirectories);
        var rfilter = new Regex(cmd.rfilter, RegexOptions.Compiled);
        var ftFile = (from afile in afiles
                      let fn = Path.GetFileName(afile)
                      where rfilter.IsMatch(fn)
                      select afile).ToArray();
        for (int i = 0; i < ftFile.Length; i++)
        {
          var ft = ftFile[i];
          Console.WriteLine();
          Console.WriteLine($"{"Item",CmdAnalysisArgs_t.nWidth}: {i + 1} / {ftFile.Length}");
          Task_ExifFile(cmd, ft);
          Task_RunExiftool(cmd, ft, exifpath);
        }
      }

      //if (args == null || args.Length == 0)
      //{
      //  using (StreamWriter sw = new StreamWriter(log, false, Encoding.GetEncoding("gb2312")))
      //  {
      //    sw.WriteLine(CmdAnalysisArgs_t.HelperString);
      //  }
      //  Process openlog = new Process();
      //  openlog.StartInfo = new ProcessStartInfo(log);
      //  openlog.Start();
      //  //Console.WriteLine(CmdAnalysisArgs_t.HelperString);
      //  //Console.ReadKey();
      //  return;
      //}
      if (cmd.isDebug || cmd.exitPause)
      {
        Console.ReadKey();
      }
    }

    public static void Task_RunExiftool(CmdAnalysisArgs_t cmd, string file, string exifpath)
    {
      // exiftool -overwrite_original -ItemList:Title="01" Love.Between.Fairy.and.Devil.2022.E01.WEB-DL.4k.H265.AAC-Xiaomi.mp4
      List<string> aArgs = new List<string>();
      aArgs.Add("-overwrite_original");
      foreach (var m1 in cmd.aMetaInfo)
      {
        var rgn = m1.replaceGroupName.Trim('\"');
        aArgs.Add($"-{m1.pyName}=\"{rgn}\"");
      }

      aArgs.Add($"\"{file}\"");
      var strArgs = string.Join(" ", aArgs);

      PathDecoderUri pdfile = new PathDecoderUri(Environment.CurrentDirectory);
      pdfile.AutoDecode(file);
      Console.WriteLine($"{"File",CmdAnalysisArgs_t.nWidth}: {pdfile.getRelType1}");
      Console.WriteLine($"{"Args",CmdAnalysisArgs_t.nWidth}: {strArgs}");
      if (!cmd.isDebug)
      {
        Process exif = new Process();
        exif.StartInfo = new ProcessStartInfo(exifpath, strArgs);
        exif.StartInfo.CreateNoWindow = true;
        exif.StartInfo.UseShellExecute = false;
        Console.WriteLine($"{"Start",CmdAnalysisArgs_t.nWidth}: exiftool");
        exif.Start();
        exif.WaitForExit();
        Console.WriteLine($"{"Cplt",CmdAnalysisArgs_t.nWidth}");
      }
    }

    public static void Task_ExifFile(CmdAnalysisArgs_t cmd, string file)
    {
      Regex rsSTRs = new Regex(@"(?<=\$)\w+(?=\$)", RegexOptions.Compiled);// 匹配 $(groupname)$
      Regex rsSTRs2 = new Regex(@"\$\w+\$", RegexOptions.Compiled); // 替换 ($groupname$)
      Regex rname = new Regex(cmd.regexName, RegexOptions.Compiled);
      string fname = Path.GetFileName(file);
      Match mfname = rname.Match(fname);
      if (mfname.Success)
      {
        foreach (var m1 in cmd.aMetaInfo)
        {
          var ss = rsSTRs.Match(m1.regexGroupName);
          if (ss.Success)
          {
            var vss = ss.Value;
            if (mfname.Groups[vss].Success)
            {
              var vssg = mfname.Groups[vss].Value;
              m1.replaceGroupName = rsSTRs2.Replace(m1.regexGroupName, vssg);
            }
          }
        }
      }
    }
  }
}
